package org.jeecg.modules.iot.middleware.util;

import io.github.yezhihao.protostar.util.Explain;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import org.yzh.protocol.basics.JTMessage;
import org.yzh.protocol.codec.JTMessageAdapter;

public class JT808Utils {
    public static final JTMessageAdapter coder = new JTMessageAdapter("org.yzh.protocol");
    public static final String getResponseCommand(String requestCommand) {
        switch (requestCommand) {
            case "0001":
                return "8001";
            case "0100":
                return "8100";
            case "0003":
                return "8003";
            case "0102":
                return "8102";
            case "8103":
                return "0103";
            case "0104":
                return "8104";
            case "8105":
                return "0105";
            case "8107":
                return "0107";
            case "0200":
                return "8200";
            case "8201":
                return "0201";
            case "8202":
                return "0202";
            case "8900":
                return "0900";
            case "0F01":
                return "8F01";
            case "8300":
                return "0300";
            case "8500":
                return "0500";
            default:
                return null;
        }
    }

    public static String encode(JTMessage message) {
        System.out.println("====================================================================================\n");
        Explain explain = new Explain();
        ByteBuf buf = null;
        try {
            buf = coder.encode(message, explain);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String hex = ByteBufUtil.hexDump(buf);
        System.out.println(message);
        System.out.println(hex);
        explain.println();
        return hex;
    }

    public static JTMessage decode(String hex) {
        System.out.println("====================================================================================\n");
        Explain explain = new Explain();
        JTMessage message = null;
        try {
            message = coder.decode(Unpooled.wrappedBuffer(ByteBufUtil.decodeHexDump(hex)), explain);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(message);
        System.out.println(hex);
        explain.println();
        return message;
    }


    public static String bytesToHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString().toUpperCase();
    }



}
